<?php
/**
 * 全局权限判断行为
 * @author zhangjie@star-net.cn
 * @copyright © ktvme. All Rights Reserved.
 * @version $Id: Validate.php 3 2017-05-08 03:02:47Z chendanming $
 */

namespace app\common\behavior;

use think\Loader;
use think\Request;
use think\Response;

class validate {
    private $acton='';
    /**
     * 全局判断是否登录（排序某些方法）
     */
    public function run() {

        $r = Request::instance();
        $c = $r->controller();
        $a = $r->action();
        $this->acton = $a;
        try{
            $validate = Loader::validate($c);
        }catch(\Exception $e){
            return true;
        }

        $arrActionName = array_filter(array_keys($validate->scene),function($v){
            return $this->acton === strtolower($v) ? true: false;
        });
        if(!empty($arrActionName)) {
            $strActionName = reset($arrActionName);

            $params = $r->param();
            if(!$validate->scene($strActionName)->check($params)) {
                if($r->isAjax()) {
                    $data = ['errorcode' => '30000', 'message' => $validate->getError()];
                    json($data, 200)->send();
                    exit();
                } else {
                    redirect('/index/index/errorPage?errorcode=40001&message='.$validate->getError())->send();
                    exit();
                }
            }
        };
        return true;
    }
}